package kotlinx.coroutines.script.tes

import androidx.lifecycle.MutableLiveData
import zx.tas.model.ActivateRequest
import zx.tas.model.ApiResult
import zx.tas.model.CKV2Info
import zx.tas.model.HeartbeatRequest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

//var apiRequestingTime = 0L

object ServerApi {
    val apiLoading = MutableLiveData<Boolean>()
    val apiRespResult = MutableLiveData<CKV2Info?>()

    fun requestActivate(cdk: String) {
        printLog { "requestActivate $cdk" }
        apiLoading.value = true
        appScopeLaunch(Dispatchers.IO) {
            val resp = try {
                api.activate(ActivateRequest(cdk))
            } catch (e: Throwable) {
                e.printStackTrace()
                null
            }
            withContext(Dispatchers.Main) {
                apiLoading.value = false
                printLog { "requestActive resp ${resp?.code} ${resp?.message} ${resp?.data?.jsonString}" }
                try {
                    val msg = resp?.message ?: ""
                    if (resp?.code == 0) {
                        toast((msg).let { it.ifEmpty { "激活成功" } } )
                        apiRespResult.value = resp.data
                        analysisEvent("Api_激活成功")
                    }
                    else {
                        toast((msg).let { it.ifEmpty { "激活失败" } } )
                        writeToDisk("keyErr", "[atv:${resp?.code}:${msg}]")
                        analysisEvent("Api_激活失败_${resp?.code}")
                    }
                } catch (e: Throwable) {
                    e.printStackTrace()
                    toast("未知错误9")
                }
            }
        }

//        printLog { "requestActivate $cdk" }
//        apiLoading.value = true
//        appScopeLaunch(Dispatchers.IO) {
//            // https://huganya.com/c/a
//            // https://tinybot.top/c/a
//            val url = AESUtils.decrypt("immortal", "8SPvkLTI2fyMB3xdFcPRMv1AL44fp7bqqd3sT4Oz+0A=")
//            apiRequestingTime = System.currentTimeMillis()
//            val clientTime = apiRequestingTime.toString()
//            val header = mapOf(
//                "r" to "imm",
//                "bt" to appBuildTime.toString(),
//                "b" to Build.BRAND,
//                "m" to Build.MODEL,
//                "osv" to Build.VERSION.SDK_INT.toString(),
//                "vn" to appVersionName,
//                "w" to phoneDefaultDisplayPoint.x.toString(),
//                "h" to phoneDefaultDisplayPoint.y.toString(),
//                "dpi" to phoneDensityDpi.toString(),
//                "t" to clientTime.toString(),
//                "a" to "s$appDeviceId$clientTime".md5)
//            val params = mapOf("d" to appDeviceId, "c" to cdk)
//            val resp = HttpRequest.invokePost(url, header, params)
//            printLog { "requestActivate resp:\n$resp" }
//            withContext(Dispatchers.Main) {
//                apiLoading.value = false
//                try {
//                    val json = JSONObject(resp ?: "{}")
//                    val code = json.optInt("code", -99)
//                    val msg = json.optString("message")?:""
//                    toast((msg).let { it.ifEmpty { "激活失败" } } )
//                    if (code == 0) {
//                        apiRespResult.value = fromJson(json.optString("data"), CKV2Info::class.java)
//                        analysisEvent("Api_激活成功")
//                    }
//                    else {
//                        writeToDisk("keyErr", "[atv:${code}:${msg}]")
//                        analysisEvent("Api_激活失败_${code}")
//                    }
//                } catch (ignored: Throwable) {
//                }
//            }
//        }
    }

    suspend fun requestHeartbeat(type: String): ApiResult<String?>? {
        return withContext(Dispatchers.IO) {
            try {
                val result = api.heartbeat(HeartbeatRequest(type))

                if (result.code == 0) analysisEvent("Api_心跳_${type}_Success")
                else analysisEvent("Api_心跳_${type}_Fail_${result.code}")

                result
            } catch (e: Throwable) {
                e.printStackTrace()
                analysisEvent("Api_心跳_${type}_Error")
                analysisEvent("Api_心跳_${type}_Error_${e.message}")
                null
            }
        }
//        return withContext(Dispatchers.IO) {
//            printLog { "requestHeartbeat $type" }
//            // https://huganya.com/c/h
//            // https://tinybot.top/c/h
//            val url = AESUtils.decrypt("immortal", "8SPvkLTI2fyMB3xdFcPRMk0O3D2VudcWex2SbZzwr8Y=")
//            apiRequestingTime = System.currentTimeMillis()
//            val clientTime = apiRequestingTime.toString()
//            val header = mapOf(
//                "r" to "imm",
//                "bt" to appBuildTime.toString(),
//                "b" to Build.BRAND,
//                "m" to Build.MODEL,
//                "osv" to Build.VERSION.SDK_INT.toString(),
//                "vn" to appVersionName,
//                "w" to phoneDefaultDisplayPoint.x.toString(),
//                "h" to phoneDefaultDisplayPoint.y.toString(),
//                "dpi" to phoneDensityDpi.toString(),
//                "t" to clientTime,
//                "a" to "s$appDeviceId$clientTime".md5)
//            val params = mapOf("type" to type,"c" to (Properties.ckV2Info?.value ?: ""), "s" to (Properties.sessionId ?: ""), "d" to appDeviceId, "tk" to Properties.scene)
//            val resp = HttpRequest.invokePost(url, header, params)
//            printLog { "requestHeartbeat resp:\n$resp" }
//            val json = try {
//                JSONObject(resp ?: "{}")
//            } catch (e: Throwable) {
//                e.printStackTrace()
//                analysisEvent("Api_心跳_${type}_Error")
//                analysisEvent("Api_心跳_${type}_Error_${e.message}")
//                JSONObject()
//            }
//            val result = ApiResult<String?>(
//                json.optInt("code", -99),
//                json.optString("message", ""),
//                json.optString("data", "")
//            )
//            if (result.code == 0) analysisEvent("Api_心跳_${type}_Success")
//            else if (result.code != -99) analysisEvent("Api_心跳_${type}_Fail_${result.code}")
//
//            result
//        }
    }
}